<?php

namespace Slide;

use C\L\AdmController;
use C\R\Slide as SlideResource;

class SlideController extends AdmController
{
    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page', 'int', 1);
        $perPage     = $this->request->getQuery('per_page', 'int', 20);
        $type        = $this->request->getQuery('type');

        $slides = $this->s_slide->paginate($type, null, $currentPage, $perPage);

        return $this->success($slides);
    }

    public function configAction()
    {
        $config = $this->s_slide->getConfig();

        return $this->success($config);
    }

    public function viewAction()
    {
        $id = $this->request->getQuery('id', 'string');

        $slide = $this->s_slide->view($id);

        if (!$slide) {
            return $this->error('查找轮播图失败');
        }

        $resource = new SlideResource($slide);

        return $this->success($resource->toArray());
    }

    public function createAction()
    {
        $params = $this->getParams();

        $slide = $this->s_slide->store($params);

        if (!$slide) {
            return $this->error('添加轮播图失败');
        }

        $resource = new SlideResource($slide);

        return $this->success($resource->toArray());
    }

    public function updateAction()
    {
        $id = $this->request->getPost('id', 'string');

        $params = $this->getParams();

        $slide = $this->s_slide->newUpdate($id, $params);

        if (!$slide) {
            return $this->error('更新轮播图失败');
        }

        $resource = new SlideResource($slide);

        return $this->success($resource->toArray());
    }

    public function deleteAction()
    {
        $id = $this->request->getPost('id', 'string');

        return $this->s_slide->delete($id)
          ? $this->success()
          : $this->error('删除轮播图失败');
    }

    private function getParams()
    {
        return [
            'name'      => $this->request->getPost('name', 'string'),
            'image_url' => $this->request->getPost('image_url', 'string'),
            'url'       => $this->request->getPost('url', 'string'),
            'types'     => $this->request->getPost('types', 'string'),
            'status'    => $this->request->getPost('status', 'int'),
            'sort'      => $this->request->getPost('sort', 'int'),
        ];
    }
}
